package com.ubirouting;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.widget.Toast;

import com.city.parking.ParkingApp;
import com.city.parking.ParkingItem;
import com.city.parking.util.SharePrefUtil;
import com.ubirouting.ubimaplib.Loader;
import com.ubirouting.ubimaplib.UbiMapDownloadListener;
import com.ubirouting.ubimaplib.data.UbiMapDownloader;

public class IndoorMap {
	private ArrayList<String> buildingJsons;
	private ArrayList<String> mapNames;
	private Context mContext;
//	private VBuilding building;
	public static final String CACHE_PATH = Environment
			.getExternalStorageDirectory().getAbsolutePath().toString()
			+ "/ShiTuGLMap/";
	private int lastPark = -1;
//	private int mall = -1;
	private long mapId;
	private String url = "";
	
	private UbiMapDownloader mMapDownloader;
	private ProgressDialog mDownloadDialog;
	
	private class Desc {
		public static final String NAME = "name";
		public static final String MALLID = "mall_id";
		public static final String SCALE = "scale";
		public static final String ANGLE = "angle";
		public static final String LAT = "lat";
		public static final String LNG = "lng";
		public static final String KEY = "key";
		public static final String HOST = "host";
		public static final String PORT = "port";
		public static final String TYPE = "loc_type";
		public static final String BLK = "blacklist";
		public static final String WHT = "whitelist";
		public static final String MACS = "blackmacs";
		public static final String FLOOR_NUMS = "floor_nums";
		public static final String FLOOR_NAME = "floor_names";
		public static final String FLOOR_DATA = "floors_data";
	}

//	public VBuilding getBuilding() {
//	//	return building;
//	}
//
//	public void setBuilding(VBuilding building) {
//	//	this.building = building;
//	}

	public IndoorMap(Context ctx) {
		mContext = ctx;
	}
	
	public void init(final Activity activity) {
//		ShiTuMapSDKInitializer.initialize(mContext, CACHE_PATH);
//		File dir = new File(CACHE_PATH);
//		if (dir != null && !dir.exists()) {
//			dir.mkdirs();
//		}
//		loadBuildings();
		
		Loader.loadWindowParas(activity);

		// Try to download resource file which contains the necessary texture
		// for map rendering. If resource file has been already download, then
		// UbiMapDownloader won't download unless there is an new version of
		// resource file.
		// **IMPORTANT** : SHOULD BE INVOKED IN UI THREAD.
		mMapDownloader = new UbiMapDownloader();
		
		mMapDownloader.tryDownloadRes(new UbiMapDownloadListener() {

			// If no resource file should be downloaded.
			@Override
			public void onNoNeedDownload() {
				// Usually do nothing here
			}

			// Downloading failed, may caused by network problem.
			@Override
			public void onFailed(final String arg0) {
				ParkingApp.showToast("download failed because of " + arg0);
				if (mDownloadDialog != null)
					mDownloadDialog.dismiss();
			}

			// On downloading, and 'percent' indicates the process of
			// downloading.
			@Override
			public void onDownloading(final float percent) {
				mDownloadDialog.setMessage("downloading resource.." + (int) (percent * 100) + "%");
			}

			// On download succeeds.
			@Override
			public void onDownloadSuccess() {
				mDownloadDialog.dismiss();
			}

			// On download starts.
			@Override
			public void onDownloadStart() {
				if (mDownloadDialog != null)
					mDownloadDialog.dismiss();

				mDownloadDialog = new ProgressDialog(activity);
				mDownloadDialog.setMessage("downloading resource..");
				mDownloadDialog.setCancelable(false);
				mDownloadDialog.show();
			}
		});
		
	}
	
//	private void loadBuildings() {
//		buildingJsons = new ArrayList<String>();
//		mapNames = new ArrayList<String>();
//		try {
//			InputStream is = mContext.getAssets().open("buildingdata.json");
//			BufferedReader reader = new BufferedReader(
//					new InputStreamReader(is));
//			String line;
//			StringBuffer buffer = new StringBuffer();
//			while ((line = reader.readLine()) != null) {
//				buffer.append(line);
//			}
//			JSONObject rootObj = new JSONObject(buffer.toString());
//			JSONArray buildingArray = rootObj.getJSONArray("json");
//			for (int i = 0; i < buildingArray.length(); i++) {
//				JSONObject buildingObj = buildingArray.getJSONObject(i);
//				String mapName = buildingObj.getString("floors_data");
//				mapName = mapName.substring(mapName.lastIndexOf("/") + 1);
//				mapNames.add(mapName);
//				String buildingData = buildingObj.toString();
//				buildingJsons.add(buildingData);
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//	}

//	public boolean saveFile(File file, InputStream input) {
//		int num_read;
//		try {
//			FileOutputStream fos = new FileOutputStream(file, false);
//			byte buf[] = new byte[1024];
//			while ((num_read = input.read(buf)) != -1) {
//				fos.write(buf, 0, num_read);
//				fos.flush();
//			}
//			fos.close();
//			return true;
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return false;
//	}
//	
	private boolean parseIndoorMap(ParkingItem park) {
//		if (park.mapAddr == null || park.mapAddr.equals(""))
//			return false;
//		try {
//			JSONObject json = new JSONObject(park.mapAddr);
//			//url = json.getString(Desc.FLOOR_DATA);
//			mall = json.getInt(Desc.MALLID);
//		} catch (JSONException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//			return false;
//		}
		mapId = 5001002586L;
		
		return true;
	}
	
	public void show(final ParkingItem park, final Activity prev) {
		if (lastPark != park.id) {
			if (!parseIndoorMap(park)) {
            	ParkingApp.showToast("本停车场暂无室内地图，请谅解");
            	return;
			}
			lastPark = park.id;
		}
		
		mMapDownloader.tryDownloadMap(mapId, new UbiMapDownloadListener() {

			@Override
			public void onNoNeedDownload() {
				// Usually do nothing
				Intent i = new Intent();
				i.putExtra("mapId", mapId);
				i.setClass(prev, IndoorMapActivity.class);
				prev.startActivity(i);
			}

			@Override
			public void onFailed(String arg0) {
				// Must check the NULL situation of mDownloadDialog, because
				// the
				// onDownloadStart() is
				// only invoked when there is a new version of map to be
				// downloading.
				if (mDownloadDialog != null)
					mDownloadDialog.dismiss();
				Toast.makeText(prev, "download failed because of " + arg0, Toast.LENGTH_LONG).show();
			}

			@Override
			public void onDownloading(float percent) {
				mDownloadDialog.setMessage("downloading map.." + (int) (percent * 100) + "%");
			}

			@Override
			public void onDownloadSuccess() {
				mDownloadDialog.dismiss();

				Intent i = new Intent();
				i.putExtra("mapId", mapId);
				i.setClass(prev, IndoorMapActivity.class);
				prev.startActivity(i);
			}

			@Override
			public void onDownloadStart() {
				if (mDownloadDialog != null)
					mDownloadDialog.dismiss();

				mDownloadDialog = new ProgressDialog(prev);
				mDownloadDialog.setMessage("downloading map..");
				mDownloadDialog.setCancelable(false);
				mDownloadDialog.show();

			}
		});
		

//		ParkingApp.get().showProgressBar(prev);
//		new Thread() {
//            @Override
//            public void run() {
//        		String name = url.substring(url.lastIndexOf("/") + 1);
//                File file = new File(CACHE_PATH + name);
//            	if (!file.exists()) {
//	                InputStream is = getInputStream(url);
//	                if (is == null || !saveFile(file, is)) {
//	                	ParkingApp.showToast("下载室内地图数据失败，请稍后再试");
//	            		ParkingApp.get().hideProgressBar();
//	                	return;
//	                } else {
//	        			VDataBuilder.parseData(name);	
//	                }
//            	}
//        		building = new VBuilding(park.mapAddr);
//        		ParkingApp.get().hideProgressBar();
//        		
//        		Intent i = new Intent();
//        		//正在加载的室内地图第一层，以及建筑id
//        		i.putExtra("mall", mall);
//        		i.setClass(prev, IndoorMapActivity.class);
//        		prev.startActivity(i);
//            }
//		}.start();
	}
	
//	public InputStream getInputStream(String urlStr)  {
//		InputStream is = null;
//		try {
//			URL url = new URL(urlStr);
//			HttpURLConnection urlConn = (HttpURLConnection) url
//					.openConnection();
//			urlConn.setRequestProperty("Connection", "close");
//			urlConn.connect();
//			is = urlConn.getInputStream();
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//
//		return is;
//	}
}
